package com.appbee.core.client.place;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;
import com.google.gwt.place.shared.Prefix;

public class IndexPlace extends Place implements INamePlace
{
	private String name;
	private int index = -1;
	
	public IndexPlace(){}
	
	public IndexPlace(String name,int index)
	{
		this.name = name;
		this.index = index;
	}

	@Override
	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	
	@Override
	public String[] getPathElements()
	{
		return name.split("_");
	}

	@Override
	public String getRootElement()
	{
		return getPathElements()[0];
	}

	public int getIndex()
	{
		return index;
	}

	public void setIndex(int index)
	{
		this.index = index;
	}


	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + index;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		IndexPlace other = (IndexPlace) obj;
		if (index != other.index)
			return false;
		if (name == null)
		{
			if (other.name != null)
				return false;
		}
		else if (!name.equals(other.name))
			return false;
		return true;
	}


	@Prefix("i")
	public static class Tokenizer implements PlaceTokenizer<IndexPlace>
	{

		@Override
		public IndexPlace getPlace(String token)
		{
			String[] split = token.split(":");
			IndexPlace p = new IndexPlace();
			if(split.length>0) p.setName(split[0]);
			if(split.length>1) p.setIndex(Integer.parseInt(split[1]));
			return p;
		}

		@Override
		public String getToken(IndexPlace place)
		{
			if(place==null) return "";
			
			StringBuffer sb = new StringBuffer();
			sb.append(place.getName());
			if (place.getIndex() > 0)
			{
				sb.append(":");
				sb.append(place.getIndex());
			}
			return sb.toString();
		}
		
	}
}
